Lesson 2: Printer Friendly

Advanced PHP Programming

Printing This Lesson

Select what you’d like to include when you print, and then click the Print Lesson button:

Saving This Lesson

For instructions on saving this lesson (shown below), please select the browser you're using.

chrome icon
Chrome
Firefox icon
Firefox
Internet Explorer 10 icon
IE
Safari icon
Safari

Firefox

If you'd like to access the lessons of this course when you're offline, as well as after the course has ended, it's easy to download them. First, you may want to create a folder to put all the lessons in so you have them in one place at the end of the course. Next, just follow the downloading instructions below.

  1. Choose Firefox >Save Page As.

  2. Choose Save Page As

  3. Specify the folder you want to save the file in, as you would with any other document.
  4. Type a name for the lesson. You can use the long suggested name or make up a shorter name of your own. However, do not add your own extension to that filename.
  5. Choose Web Page, complete as the file type.

  6. Use Web Page, complete as the file type

  7. Click Save.

Viewing Downloaded Lessons

After you've downloaded a lesson, you can use these steps at any time to open, view, or print it. You don't need to be connected to the Internet.

  1. Open the folder you saved the lesson in.
  2. You'll likely see two icons per downloaded lesson, as in the example below.

  3. Icons for one lesson saved as Web Page, complete

  4. To view the lesson, double-click the file with the *.htm extension (the one that looks like a dog-eared piece of paper). Opening the folder icon won't show you the lesson; it will only display icons for extra files that the lesson needs to display properly.
  5. If you have multiple programs for opening *.htm files, you can right-click the icon (or CONTROL + click the icon if you're using a Mac) and choose Open With. You'll be able to select Firefox to open and view the lesson.

Missing Pictures

If you open a downloaded lesson and some pictures are missing, you might not have waited long enough for the pictures to download before clicking Save. Interactive content, such as videos or games, may not save. Another possibility is that you may have downloaded using one browser (like Firefox) but opened using a different browser (like Internet Explorer). Try opening the downloaded lesson with the same browser you used to download the lesson (please see step #4 above).

Chapter 1

Introduction

Welcome back! I hope you have your WampServer up and running and that you've shaken the cobwebs from your PHP knowledge. Today we're going to dive in and look at some more PHP coding techniques before we start working on the actual course project code. You'll learn three PHP features that will be crucial to our storefront operation.

First, we'll look at how to easily retrieve data contained in an array. You'll need to know that because the customer shopping cart in our storefront Web app will use array variables. Using array variables is handy, but it complicates retrieving data, especially when you don't know all of the data keys (which we won't). You'll learn a way to easily solve this problem.

Next, we'll explore a feature in PHP that is extremely handy: functions. I'm sure you've used built-in PHP functions before, but today we'll see how to create our own customized functions.

Finally, we'll have a look at the functions PHP includes for handling images. We'll be incorporating dynamic images in our storefront application, but before we can do that, we'll need to learn some PHP functions that will help us handle them.

That should keep us busy! Let's move on to Chapter 2 and get started.

Chapter 2

Iterating Through Arrays

Hopefully, you've seen PHP array variables by now in your PHP programming experience. An array variable is a single variable that can contain multiple values. The array references each individual value using a key, sort of like a database. Each key references a single data value contained in the array. PHP provides two different types of keys you can use to reference values:

  • Numeric keys
  • Associative keys

A numeric array variable is what you're probably used to if you've used arrays in other programming languages. The numeric array variable uses numbers for keys to reference values in the array. The key numbers always start at zero and increase as you store new values in the array.

There are two ways to create a numeric array variable. First, you can create the array using the PHP array() function:

$myarray = array(10, 20, 30, 40, 50);

This code creates a numeric array variable called $myarray and assigns five values to the array. You can access the individual array values by using their numeric location in the array (starting at location zero). Just specify the numeric location of the desired array element in square brackets next to the variable name.

$test = $myarray[0] + $myarray[1];

This code adds the values stored in the first and second $myarray array elements (which would be the values 10 and 20).

The second way to create a numeric array variable is to assign values to individual array elements, like this:

$myarray = array();
$myarray[0] = 10;
$myarray[1] = 20;
$myarray[2] = 30;
$myarray[3] = 40;
$myarray[4] = 50;

Before you can assign the individual elements, you need to tell PHP that the $myarray variable is going to be an array variable. You do this by using the empty array() function.

The array values don't have to be numbers. You can also store string values in an array:

$myarray = array();
$myarray[0] = "Rich";
$myarray[1] = "Barbara";
$myarray[2] = "Katie";
$myarray[3] = "Jessica";
echo "The first person in the array is {$myarray[0]}";

Notice the echo statement in the code. You must be careful when using arrays in echo statements. If you want to use an array variable in an echo statement, you must enclose it in braces to separate it from the rest of the text. Otherwise PHP gets confused.

Associative Array Variables

Associative array variables use strings as keys. This can sometimes get confusing, but it provides a powerful tool for storing information. Similar to the numeric arrays, there are two ways you can create a new associative array variable. The first way uses the array() function:

$myarray = array("state"=>"Illinois", "city"=>"Chicago", "zip"=>"60633");

This statement creates three associative keys for the $myarray array variable and assigns values to each key. The funny looking => symbol assigns the value to the key. In this example, I associate each key with a string value, but you can use numerical values as well.

With the associative array, you must use the string key to recall the stored value:

echo "The state is {$myarray['state']}";

You also create the individual array elements as you would with numeric array variables.

$myarray = array();
$myarray['state'] = "Illinois";
$myarray['city'] = "Chicago";
$myarray['zip'] = "60633";
echo "The state is {$myarray['state']}";

Just as with the numeric array variables, if you want to use an associative array variable in an echo statement, you must include braces around it.

Listing Values Stored in the Array

The tricky part of working with arrays is extracting all of the data they contain. If you use associative array variables, you may have no way of knowing what key values the array contains. Even if you use numeric array variables, there's no guarantee that the key numbers are sequential (you can assign a value to $myarray[6] without assigning a value to $myarray[3], $myarray[4], or $myarray[5]).

Fortunately for us, those thoughtful programmers who developed PHP came up with a simple solution. The foreach statement iterates through an array, extracting every key/value pair defined within the array, one at a time.

There are a couple of ways to use the foreach statement with an array. The first method only extracts the value stored in the array, without regard to the key:

$myarray = array("state"=>"Illinois", "city"=>"Chicago", "zip"=>"60633");
foreach ($myarray as $value)
{
echo "The value is $value<br>\n";
}

In this code snippet, the foreach statement loops through the $myarray array variable. Each value stored in the array is extracted as the variable $value and can be used anywhere within the foreach loop. Notice that the $value variable is a normal variable and can be used without requiring the braces.

The second way to extract array values pulls the entire key/value pair.

$myarray = array("state"=>"Illinois", "city"=>"Chicago", "zip"=>"60633");
foreach($myarray as $key=>$value)
{
echo "The $key value is $value<br>\n";
}

Now you have access to both the key and the data value within the array. Again, the $key and $value variables are normal variables you can use anywhere within the foreach loop to represent the key and data value. We'll be using this feature in our shopping cart to extract items our customers purchase.

In the next chapter, we'll take a look at a PHP feature that will help reduce the amount of code typing we need to do in our applications!

Chapter 3

Creating PHP Functions

I'm sure you've been using built-in PHP functions in your applications. Functions are nothing more than PHP code someone else wrote that you can use. Instead of having to copy all of the code into your application, you just use the function name, such as when we use the mysql_connect() function to connect to a MySQL server.

PHP also allows us to create our own functions to use in programs and share with others. Once you define a function, you can use it throughout your program. This saves typing if you use a common routine or block of code in lots of places in your application. All you need to do is write the code once as a function and then call the function everywhere else it appears in the application!

The basic format for a function looks like this:

function name(parameters)
{
function code
return value
}

The function name must uniquely identify the function. It can't be one of the existing function names in PHP, and it can't start with a number (although numbers can appear anywhere else in the function name).

The function parameters identify one or more variables that the calling program passes to the function (actually, you can also have a function that uses no parameters). If there is more than one variable, you must separate them using commas. You can use the variables anywhere within the function code, but they only apply to the function. You can't access the passed variables anywhere else in your PHP code.

It's important to note that any variables you define within the function apply only to the function. You can't use any function variables in your outside PHP code.

At this point you might be saying, "But I perform this really cool calculation in my function! How do I pass the answer back to my program if I can't share variables?" That's the purpose of the return statement.

The return statement is the last statement in the function. It defines a single function variable that the function returns to the calling program. Thus, you can only pass one variable back to the rest of the PHP program.

The best way to learn functions is to start building them. Let's look at an example:

<?php

function factorial($value1)
{
$factorial = 1;
$count = 1;
while($count <= $value1)
{
$factorial = $factorial * $count;
$count = $count + 1;
}
return $factorial;
}

echo "The factorial of 10 is " . factorial(10) . "<br>\n";
echo "The factorial of 5 is " . factorial(5) . "<br>\n";
?>

Notice that all of the factorial code is self-contained within the function braces. When the PHP program uses the new factorial() function, it passes a single value that the function assigns to the $value1 variable. The function returns the final factorial result.

Remember, you can't use the actual $factorial variable in your PHP code because it's defined inside the function. Instead, the factorial function now represents the value the function returns in the code. This can be somewhat difficult to grasp if you've never used functions before.

When you use the function in your PHP code, it acts like a variable in that the value it returns appears wherever you declare the function. Let's see how this works by testing it out.

  1. Create a file in the WampServer www folder called functest.php.
  2. Open the file using Microsoft Notepad or your favorite text editor.
  3. Enter the code snippet from the factorial function example shown earlier.
  4. Save the functest.php file.
  5. noteNote: If you're using Microsoft Notepad to edit and save your PHP files, be careful when saving. You must put double quotes around the filename in the Save As dialog box (like "functest.php"), or Notepad will add a .txt extension to the file.

  6. Open a browser window, and go to http://localhost/functest.php
  7. .

You should see the output of the functest.php program as shown below.

The functest.php program output

The functest.php program output

Notice how the result from the function appears exactly where you place the function in the echo statement.

Creating Function Libraries

The functest.php example defines the factorial function at the top of the program code and then uses it later in the same program. This isn't a requirement. You can define the function anywhere in the PHP code and then use it anywhere else in the same code. What comes in real handy, though, is creating a function library file.

You can define the function in a completely separate file, then use the PHP include() function to add the function code to your PHP program. This lets you create the function once and use it in as many programs as you want without having to retype it!

Let's test this feature out. First, create the factorial function file.

  1. Create a file in the WampServer www folder called factorial.php.
  2. Open the file using Microsoft Notepad or your favorite text editor.
  3. Enter the following PHP code:
  4. <?php
    function factorial($value1)
    {
    $fact = 1;
    $count = 1;
    while($count <= $value1)
    {
    $fact = $fact * $count;
    $count = $count + 1;
    }
    return $fact;
    }
    ?>

  5. Save the factorial.php file.
  6. Create another file in the WampServer www folder called functest2.php.
  7. Open the file using Microsoft Notepad or your favorite text editor.
  8. Enter the following PHP code:
  9. <html>
    <body>
    <h2>This is a test of defining a function in a separate file</h2>
    <?php
    include("factorial.php");

    echo "The first test. The factorial of 3 is " . factorial(3) . "<br>\n";
    ?>

    <h2>Now, let's try to use it again</h2>

    <?php
    echo "The last factorial test. The factorial of 5 is " . factorial(5) . "<br>\n";
    ?>

    <h2>This is the end of the test</h2>
    </body>
    </html>

  10. Save the functest2.php file.
  11. Open your browser, and go to http://localhost/functest2.php.
  12. You should see something that looks like this:

    The output from the functest2.php program

    The output from the functest2.php program

    Notice that after using the include() function to add the factorial.php code to your program, your new factorial() function worked no matter where in the Web page you used it! This is a great time-saving feature of PHP.

    Okay, enough about functions. Let's move on to the next topic—handling images.

Chapter 4

Handling Images

Besides its normal HTML duties, PHP also has functions to handle lots of different types of image files. The php_gd2 extension library includes functions for creating and manipulating image files in various formats, such as GIF, JPEG, and PNG. You'll use some of the PHP image functions to help create and manipulate images for your storefront Web site. Before you can do that, though, you need to make sure you've installed the php_gd2 extension in your AMP server.

Installing the GD2 Extension

The WampServer provides an excellent user interface for handling PHP extensions. All you need to do is find the php_gd2 entry in the extensions menu and select it. Here are the steps to do that:

  1. Start the WampServer services on your PC.
  2. Click the WampServer icon in the system tray.
  3. Select the PHP entry in the pop-up menu.
  4. Select the PHP Extensions entry in the PHP Settings menu.
  5. Select the php_gd2 entry in the PHP Extensions menu.
  6. Select the Stop All Services entry from the WampServer menu.
  7. Select the Start All Services entry from the WampServer menu.
  8. You're now ready to start playing with images in your PHP applications.

    noteNote: If you're using an ISP AMP server, you'll have to consult with your ISP to find out whether they have the php_gd2 extension loaded. Depending on their setup, you may not be able to load it yourself. But it's a fairly common extension; so chances are they already have it loaded.

    Creating a New Image File

    One of the exciting features in the GD2 library is the ability to create our own image files. Much like the Microsoft Paint program, the PHP GD2 library allows us to create a blank canvas and then draw lines, shapes, add text, set colors, and save it as an image file.

    To create a new image, use the imagecreatetruecolor() function. This function takes two parameters: the width and height of the new image specified in pixels. It returns a value that you must use to reference the new image while working in the main program. For example, the code below creates a new image that is 80 pixels wide by 60 pixels high. This is a common image size for what's commonly called a thumbnail image. A thumbnail image is a smaller image that easily fits on a Web page.

    $image = imagecreatetruecolor(80, 60);

    After creating a new image, you'll probably want to draw in it. First, you must allocate colors to use for drawing your objects. The imagecolorallocate() function does this.

    $bc = imagecolorallocate($image, 255, 255, 255);
    $fc = imagecolorallocate($image, 0, 0, 0, 0);

    The imagecolorallocate() function takes four parameters. The first parameter is the image returned by the imagecreatetruecolor() function. The next three parameters are a color hue defined using the Red-Green-Blue (RGB) values commonly used in CSS style sheets. Each value is one byte in size, and you can specify them using either decimal or hexadecimal values. The combination 255, 255, 255 represents white, while the combination 0, 0, 0 represents black.

    After allocating the colors you want to use, you can start drawing. The GD2 library includes several functions for drawing lines, shapes, and text.

    Some GD2 Library Drawing Functions
    Function Description
    imageline() Draw a line between two specified points using a defined color.
    imagechar() Draw an alphanumeric character using a specified font, color, and location.
    imagerectangle() Draw a rectangle between four specified points using a specified color.
    imagefilledrectangle() Draw a solid rectangle between four specified points, filling it with a specified color.
    imagestring() Draw a string of characters using a specified font, color, and location.

    Let's build a small PHP program that creates a sample image file. In our storefront application, we'll need a generic image to display when an image for an item isn't available. Follow these steps to create that image.

    1. Create a file in the WampServer www folder called createimage.php.
    2. Open the file using Notepad, and enter the following code:

      <?php

      $image = imagecreatetruecolor(80, 60);

      $bc = imagecolorallocate($image, 255, 255, 255);
      $fc = imagecolorallocate($image, 0, 0, 0);

      imagefilledrectangle($image, 0, 0, 80, 60, $bc);
      imagestring($image, 5, 20, 5, "No", $fc);
      imagestring($image, 5, 10, 20, "Image", $fc);
      imagestring($image, 5, 0, 35, "Available", $fc);

      imagejpeg($image, "noimage.jpg");
      imagedestroy($image);

      echo "Image created";
      ?>

    3. Save the file, and exit Notepad.
    4. Open a browser window, and go to http://localhost/createimage.php.

    You should recognize most of the image functions here. The imagestring() function specifies a font size, followed by the X and Y coordinates of where you want the string to start, then the actual string, and finally, the color to use to draw the string.

    The imagejpeg() function takes your newly created image and either displays it on the Web page or, in our case, writes it to a file as a JPEG image. After we're done, we use the imagedestroy() function to free up the memory associated with our image.

    When you run the program, you won't see anything too exciting in your browser window—just a message saying the image was created. However, if you go to the www folder in the WampServer area, you'll see a new file called noimage.jpg! If you open that file with your default JPEG viewer, you should see your new image.

    The noimage.jpg file

    The noimage.jpg file

    The imagestring() functions drew our strings on the image canvas to create the "No Image Available" image for our application. Set this image aside for now. We'll use it later.

    Modifying Existing Images

    One of the biggest problems in using images on Web pages is they are often too big. If you run a Web site that allows visitors to upload pictures, you never know quite what to expect. Some visitors upload picture files that are 300 x 500, while others upload picture files that are 1024 x 768! The trick is to standardize all of your images so they will fit nicely in your Web pages. Fortunately, the PHP GD library has just the tools for us!

    The imagecopyresampled() function allows us to resample an existing image file to a new image. Resampling rebuilds the picture pixel by pixel at a different resolution using special algorithms to maintain the picture clarity. By resampling, we can either shrink or expand the image. The GD2 library handles all of the complicated mathematical routines required to do that. We'll use this technique to make all the images in our storefront Web site the same size.

    In the meantime, here's some sample code you can use to create a test file and resample some JPEG images you have laying around:

    <?php

    $image = file_get_contents("test.jpg");
    $source = imagecreatefromstring($image);

    $width = imagesx($source);
    $height = imagesy($source);

    $thumb = imagecreatetruecolor(80, 60);
    imagecopyresampled($thumb, $source, 0, 0, 0, 0, 80, 60, $width, $height);
    imagejpeg($thumb, "newthumb.jpg");

    echo "image created";
    ?>

    This example takes an original image called test.jpg and resizes it to a small thumbnail-sized image called newthumb.jpg.

    First, we use the PHP function file_get_contents() to read the image file into a PHP variable. (Yes, you can store the entire contents of a file in a single PHP variable!) Next, we use the imagecreatefromstring() function that converts the contents of the variable into a new image we can manipulate.

    In order to resize the image, the GD2 library needs to know the existing size of the image. We use the imagesx() function to get the width of the image and the imagesy() function to get the height of the image.

    The next step is to create our new image that's the size we want using the imagecreatetruecolor() function. For this test, we'll use our 80 x 60 thumbnail size. Now that we have our original image and our new image, we use the imagecopyresampled() function to copy the original image to the new image using the new image size.

    You must specify the destination image, source image, starting X and Y locations in the destination and source, and the width and height of the destination and source. To make our thumbnail image, we specify the destination width and height as 80 x 60.

    Finally, we use the imagejpeg() function to convert the image to JPEG format and store it in a file called newthumb.jpg.

    Let's test this out.

    1. Create a new file in the WampServer folder called makethumb.php, and then copy the example code shown above into it. Save the file.
    2. Copy a JPEG image you have laying around to the WampServer www folder, and rename it test.jpg.
    3. Go to http://localhost/makethumb.php.

    Again, the Web page won't be too exciting, but now look in your www folder. You should see the newthumb.jpg file. It will be a shrunken version of the original JPEG file you used for testing!

    That's enough PHP code for one day. Follow me to the summary, and we'll wrap up today's lesson.

Chapter 5

Summary

We've done a lot today. First off, we discussed handling data stored in array variables. You saw how the PHP foreach statement helps us iterate through all of the array keys and values, even when we don't know what they are. This technique will become invaluable to us as we work with our customer shopping cart.

After that, we dove into the topic of PHP functions. You saw how we can create our own customized functions that can be used anywhere, in any PHP program. This technique will save us loads of typing in our project!

Finally, we took a peek at some of the image-handling capabilities of the PHP GD2 library. The GD2 library provides lots of functions for creating our own images, as well as manipulating existing images. We'll be using some of these functions in our storefront to save and display images of our products.

In the next lesson, we'll start laying out the database environment for our application. We'll be covering some advanced database techniques that will make the storefront application more robust than just some simple text database tables.

As always, remember to do your quiz and assignment before moving on.

Supplementary Material

http://www.php.net/manual/en/ref.image.php

FAQs

Q: How can I tell if my ISP AMP server includes the php_gd2 extension?

A: If you have access to the php.ini file, check for the line:

extension=php_gd2.so


Q: What image formats do the functions in the GD2 library support?

A: You can use the GD2 library to read and write GIF, JPEG, PNG, and XPM image files. You can also use the GD2 library to obtain information from SWF, TIFF, and JPEG2000 image files, but you can't manipulate them.


Q: Can the GD2 library extract and modify the information stored in the JPEG headers?

A: No, but there's another PHP extension that can. Look for the exif extension in the PHP manual. That includes functions for manipulating the headers in JPEG files.

Assignment


For today's assignment, play around with your image files. Write some PHP code to create a new image using the imagecreatetruecolor() function. Then draw some shapes, lines, and add text within the image. Save the image using a couple of different image types, such as GIF and JPEG.

Next, load an existing image you have laying around, and then use the same image-manipulation functions on it. Can you draw lines, shapes, and add text on the existing image? After defacing your image, save it with another filename and file type.